/**
 * SwordGrid的模板描述
 */
var SwordGrid_Template = {

	'div_end' : '</div>',
	'row_dan' : '<div status="{status}" class="sGrid_data_row_div sGrid_data_row_div_dan" row="true"  pagenum="{pagenum}">',
	'row_shuang' : '<div status="{status}" class="sGrid_data_row_div sGrid_data_row_div_shuang " row="true"  pagenum="{pagenum}">',
	'row_tree' : '<div status="{status}" class="sGrid_data_row_div" row="true"  pagenum="{pagenum}">',

	'act' : '<div disable="{disable}"  format="{format}" rule="{rule}" x="{x}" act="{act}" caption=\'{caption}\' name="{name}" buttonel="true" class="sGrid_data_row_item_div sGrid_data_row_itemdiv_button <tpl if="values.get(\'disable\')==\'true\'"> sGrid_data_row_itemdiv_disabled </tpl>" style="width: {x};" eventdele="act">{caption}</div>',
	'act_a' : '<div disable="{disable}"  format="{format}"   rule="{rule}" type="a" x="{x}" act="{act}" caption=\'{caption}\' name="{name}" datael="true" class="sGrid_data_row_item_div sGrid_data_row_item_a <tpl if="values.get(\'disable\')==\'true\'"> sGrid_data_row_itemdiv_disabled </tpl>" style="width: {x}; " eventdele="act">{value}</div>',

	
	
	'label' : '<div disable="{disable}"  format="{format}"  rule="{rule}" class="sGrid_data_row_item_div sGrid_data_row_item_label <tpl if="values.get(\'disable\')==\'true\'"> sGrid_data_row_itemdiv_disabled </tpl>" type="label" datael="true" x="{x}"  caption=\'{caption}\'  name="{name}"   style="width:{x};{showStyle} " realvalue=\'{realvalue}\' title=\'{title}\'  code=\'{code}\'>{value}</div>',
	'a' : '<div disable="{disable}" format="{format}"   rule="{rule}" title=\'{title}\' realvalue="{title}" style="width:{x};{showStyle} " class="sGrid_data_row_item_div sGrid_data_row_item_a <tpl if="values.get(\'disable\')==\'true\'"> sGrid_data_row_itemdiv_disabled </tpl>" datael="true" name="{name}" caption=\'{caption}\' type="a" x="{x}"><span class="sGrid_data_row_item_a_span">{value}</span></div>',
	'button' : '<div disable="{disable}"  format="{format}"   rule="{rule}" x="{x}" type="button" caption=\'{caption}\' name="{name}" buttonel="true" class="sGrid_data_row_item_div sGrid_data_row_itemdiv_button <tpl if="values.get(\'disable\')==\'true\'"> sGrid_data_row_itemdiv_disabled </tpl>" style="width:{x};{showStyle} "><span class="sGrid_data_row_item_button_span">{caption}</span></div>',
	'checkbox' : '<div disable="{disable}"  format="{format}"   rule="{rule}" x="{x}" type="checkbox" caption=\'{caption}\' name="{name}" datael="true" class="sGrid_data_row_item_div <tpl if="values.get(\'disable\')==\'true\'"> sGrid_data_row_itemdiv_disabled </tpl>" style="width: {x};{showStyle} " userclicked="false" checkallflag="false"><input type="checkbox" name="{name}" value="{value}" class="sGrid_data_row_item_checkbox" eventdele="checkbox"    {checked}    {disabled}></div>',
	'date' : '<div disable="{disable}"  format="{format}"   rule="{rule}" x="{x}" type="date" caption=\'{caption}\' name="{name}" datael="true" class="sGrid_data_row_item_div sGrid_data_row_item_date <tpl if="values.get(\'disable\')==\'true\'"> sGrid_data_row_itemdiv_disabled </tpl>" style="width:{x};{showStyle} " eventdele="date" showvalue="{value}"  realvalue=\'{realvalue}\' title=\'{title}\' showStylevalue="{showStylevalue}">{value}</div>',
	'file2' : '<div disable="{disable}"  format="{format}"   rule="{rule}" x="{x}" type="file2" caption=\'{caption}\' name="{name}" datael="true" class="sGrid_data_row_item_div sGrid_data_row_item_div_file2 <tpl if="values.get(\'disable\')==\'true\'"> sGrid_data_row_itemdiv_disabled </tpl>" style="width: {x};{showStyle} " eventdele="file2"><div name="tmp" class="sword_file_upload2"> <ul name="up-list" class="up-list"><tpl if="data.haveData==\'true\'"><li id="file-id" class="file"><span class="file-title">{filename}</span></li></ul></tpl><tpl if="data.haveData==\'false\'"></ul><a name="up-attach" style="color: blue; text-decoration: underline; ">{addCaption}</a></tpl></div></div>',

	'password' : '<div disable="{disable}"  format="{format}"  rule="{rule}"  x="{x}" type="password" caption=\'{caption}\' name="{name}" datael="true" class="sGrid_data_row_item_div sGrid_data_row_item_password <tpl if="values.get(\'disable\')==\'true\'"> sGrid_data_row_itemdiv_disabled </tpl>" style="width:{x};{showStyle} " eventdele="text" title=\'{title}\' realvalue=\'{realvalue}\' showStylevalue="{showStylevalue}">{value}</div>',
	'pulltree' : '<div disable="{disable}"  format="{format}"   rule="{rule}" treename="{treename}" x="{x}" type="pulltree" caption=\'{caption}\' name="{name}" datael="true" class="sGrid_data_row_item_div sGrid_data_row_item_pulltree <tpl if="values.get(\'disable\')==\'true\'"> sGrid_data_row_itemdiv_disabled </tpl>" style="width:{x};{showStyle} " eventdele="pulltree" title=\'{title}\' realvalue=\'{realvalue}\'>{value}</div>',	
	'radio' : '<div disable="{disable}"  format="{format}"   rule="{rule}" x="{x}" type="radio" caption=\'{caption}\' name="{name}" datael="true" class="sGrid_data_row_item_div <tpl if="values.get(\'disable\')==\'true\'"> sGrid_data_row_itemdiv_disabled </tpl>" style="width:{x};{showStyle} "><input type="radio" name="{name}" value="{value}" class="sGrid_data_row_item_checkbox" eventdele="checkbox" {checked} {disabled}></div>',
	'rowNum' : '<div disable="{disable}"  format="{format}"  rule="{rule}"  x="{x}" type="rowNum" caption=\'{caption}\' name="{name}" datael="true" class="sGrid_data_row_item_div sGrid_data_row_item_rowNum <tpl if="values.get(\'disable\')==\'true\'"> sGrid_data_row_itemdiv_disabled </tpl>" style="width:{x};{showStyle} " >{value}</div>',
	'rowNumOnePage' : '<div disable="{disable}"  format="{format}"  rule="{rule}"  x="{x}" type="rowNumOnePage" caption=\'{caption}\' name="{name}" datael="true" class="sGrid_data_row_item_div sGrid_data_row_item_rowNumOnePage <tpl if="values.get(\'disable\')==\'true\'"> sGrid_data_row_itemdiv_disabled </tpl>" style="width:{x};{showStyle} ">{value}</div>',
	'select' : '<div disable="{disable}"  format="{format}"  rule="{rule}"  x="{x}" type="select" caption=\'{caption}\' name="{name}" datael="true" class="sGrid_data_row_item_div sGrid_data_row_item_select <tpl if="values.get(\'disable\')==\'true\'"> sGrid_data_row_itemdiv_disabled </tpl>" style="width:{x};{showStyle} " eventdele="select" title=\'{title}\' code=\'{code}\' realvalue=\'{realvalue}\' allDb=\'{allDb}\' parent="{parent}">{value}</div>',
	'text' : '<div disable="{disable}"  format="{format}"   rule="{rule}" x="{x}" type="text" caption=\'{caption}\' name="{name}" datael="true" class="sGrid_data_row_item_div sGrid_data_row_item_text <tpl if="values.get(\'disable\')==\'true\'"> sGrid_data_row_itemdiv_disabled </tpl>" style="width:{x};{showStyle} " eventdele="text" title=\'{title}\' realvalue=\'{realvalue}\' showStylevalue="{showStylevalue}">{value}</div>',
	'textarea' : '<div disable="{disable}"  format="{format}"   rule="{rule}" x="{x}" type="textarea" caption=\'{caption}\' name="{name}" datael="true" class="sGrid_data_row_item_div sGrid_data_row_item_textarea <tpl if="values.get(\'disable\')==\'true\'"> sGrid_data_row_itemdiv_disabled </tpl>" style="width:{x};{showStyle} " eventdele="text" title=\'{title}\' realvalue=\'{realvalue}\' showStylevalue="{showStylevalue}">{value}</div>',
	'userdefine' : '<div disable="{disable}"  format="{format}"   rule="{rule}" x="{x}" type="userdefine" caption=\'{caption}\' name="{name}" style="width:{x};{showStyle} " datael="true" class="sGrid_data_row_item_div sGrid_data_row_item_userdefine <tpl if="values.get(\'disable\')==\'true\'"> sGrid_data_row_itemdiv_disabled </tpl>">{html}</div>'
	
};



var SwordGridRender = new Class({
	
	Implements:[Options]

	,name : "SwordGridRender"
		
	,options:{
		gridObj:null//容器
	}
	
		
	,initialize : function(options) {
		this.setOptions(options);
		if(!this.options.gridObj)throw new Error("SwordGridRender 初始化必须要传入 gridObj");
		this.g=this.options.gridObj;
	}
	
	,render:function (datas,items) {
//    	$l.profile("render");
    	if(!items)items=this.options.items;
    	var h=[];
    	datas.each(function(rowData,i){
    		h.extend(this._createRow( rowData, items,i+1));
    		
    	},this);
//    	$l.profile("render");
    	var rows= this._toEl(h.join(""));
    	this._renderAfter(rows, datas);
    	return rows;
    }
	
	,renderRow:function(rowData, items,rowNum, status){
		var h=this._createRow(rowData, items,rowNum,status);
		var row= new Element('div',{
			'html':h
		}).getFirst();
				
		this._renderAfter([row], [rowData]);

		return row;
	}
	
	
	//私有开始。。。。。。。。
	
	,_toEl:function(html){
		var div = new Element('div',{'html':html}),
        fragment = document.createDocumentFragment();

	    return div.getChildren();

	}
	
	,_createRow:function( rowData, items,rowNum, status){
		 /*if($chk(status)) {//标记这行的状态
		        sGrid_data_row_div.set('status', status);
		    } else if($chk(dataObj['status'])) {
		        sGrid_data_row_div.set('status', dataObj['status']);
		    }
		    if(sGrid_data_row_div.get('status')=='delete'){
		        sGrid_data_row_div.addClass('sGrid_data_row_delete_div');
		    }*/
		this.g.addGV(rowData);
		var h=[];
		h.push(this._createRowDiv(rowNum,rowData));
		h.push(this._createOneRowCells(items,rowData,rowNum));
		h.push(this._getTemplate('div_end'));
		return h;
	}
	
	,_createOneRowCells:function(items,rowData,rowNum){
		var row=[];
		var l=items.length-1;
		items.each(function(item,index){
			if(index==l&&item.get("x")=="50%")item.set("x","49.99%");
			row.push(this._createCell(this._dealItem(item),rowData,rowNum));
			
		},this);
		return row.join("");
	}
	
	,_dealItem:function(item){
		if(item.get('_renderDeal')!='true'){
			item.set('_renderDeal','true');
			
			var x=item.get('x');
			if(x){
				if(!x.contains('px')&&!x.contains('%')){
					x+='px';
					item.set('x',x);
				}
			}
		}
		
		return item;
	}
	
	,_createCell:function(item,rowData,rowNum){
		var d=this._dealCellData(item,this._getCellData(item,rowData),rowData,rowNum);
		if(item.get('show')=="false"&&!item.get('showStyle')){
			item.set('showStyle','display:none;');
		}
		this.g.fireEvent("onAfterCreateCell",[rowData,item,rowNum,this.g]);
		return STemplateEngine.render(this._findTemplate(item),item,d);
	}
	,_findTemplate:function(item){
		var n=item.get('type');
		if(item.get('act')){
			if(n=="a"){
				n='act_a';
			}else{
				n='act';
			}
		}
		return this._getTemplate(n);
	}
	,_getTemplate:function(name){
		if(!name||name=='lable')name='label';
		return SwordGrid_Template[name];
	}
	,_getCellData:function(item,rowData){
		return rowData.tds[item.get('name')];
	}
	,_createRowDiv:function(rowNum,rowData){
        var status=rowData['status'];
		var g=this.g;
		var  n;
		if(g.options.type != 'tree') {//树形表格将不使用此逻辑
            if(rowNum % 2 == 0) { //偶数行
                n='row_shuang';
            } else {//奇数行 singular
            	n='row_dan';
            }
        } else { //tree
        	n='row_tree';
        }
		var row=this._getTemplate(n);
		//todo
		return STemplateEngine.render(row,null,{/*'rownum':rowNum,*/ 'pagenum':g.pageNum(),'status':status});
	}
		
	,_dealCellData:function(item,cellData,rowData,rowNum){
		var r;
		if(cellData)r=this._findDataHandler(item)(item,cellData,rowData,rowNum);
		 else if(['file2','rowNum','rowNumOnePage'].contains(item.get('type'))){//特殊的类型，在没有数据的时候也需要特殊处理
			return this._findDataHandler(item)(item,cellData,rowData,rowNum); 
		} 
		return r?r:this._getRes();
	}
	
	
	
	,_renderAfter:function(rows,datas){
    	var deletedRows=0;
    	rows.each(function(row,i){
    		if(!row.retrieve('rowData')){
    			var cells = row.getElements("div.sGrid_data_row_item_userdefine");
    			cells.each(function(cell,j){
    				var replaceBefore = ["{{=","}}","<!--#if-->","<!--#list-->","&lt;","&gt;","&quot;","lt","gt","lte","gte"];
    				var replaceAfter = ["${" ,"}" ,"</#if>","</#list>","<",">","\""," < "," > "," <= "," >= "];
    				var temp = cell.innerHTML;
   					for(var k=0;k<replaceBefore.length;k++){
   						var reg = new RegExp(replaceBefore[k], "g");
   						temp = temp.replace(reg,replaceAfter[k]);
   					}
   					if(temp.contains("_has_next")){
   						var t1 = temp.substring(temp.indexOf(" as ")+4);
   						var t2 = t1.substring(0,t1.indexOf(">"));
   						var t = t2.trim()+"_has_next";
   						temp = temp.replace(t,"i-1 != -1");
   					}
    				var x = easyTemplate(temp,eval(datas[i].tds));
    				row.getElements("div.sGrid_data_row_item_userdefine")[j].innerHTML = x;
    			});
    			
    			this._renderRowAfter(row,datas[i]);
    			this._renderCellAfter(row,i+1,deletedRows);
    			if(row.get('status')=='delete')deletedRows++;
    		}
    		this.g.fireEvent("onAfterCreateRow", [datas[i],row,this.g.items(),this.g]);
    	},this);
    }
    
    ,_renderRowAfter:function(row,rowData){
			row.store('rowData', rowData);//注册行数据
			this.g.addRowApi(row); //添加行接口
    }
    
        
   ,_renderCellAfter:function(row,rowIndex,deletedRows){
    	row.getChildren().each(function(cell){
    		this.g.addCellApi(cell);
//    		this.g._addRowNum(cell,rowIndex,deletedRows);
    	},this);
    	
    }
	
	
	,_dataHandlers:null
	,_findDataHandler:function(item){
		var type=item.get('type');
		if(!this._dataHandlers){
			this._dataHandlers={//定义特殊数据处理器
				'button':this._emptyDataHandler.bind(this)
				,'checkbox':this._checkbox_radioDataHandler.bind(this)
				,'radio':this._checkbox_radioDataHandler.bind(this)
				,'date':this._dateDataHandler.bind(this)
				,'file2':this._file2DataHandler.bind(this)
				,'text':this._textDataHandler.bind(this)
				,'hidden':this._textDataHandler.bind(this)
				,'password':this._textDataHandler.bind(this)
				,'textarea':this._textDataHandler.bind(this)
				,'pulltree':this._pulltreeDataHandler.bind(this)
				,'rowNum':this._rowNumDataHandler.bind(this)
				,'rowNumOnePage':this._rowNumOnePageDataHandler.bind(this)
				,'select':this._selectDataHandler.bind(this)
				,'userdefine':this._emptyDataHandler.bind(this)
			};
		}
		
		if(this._dataHandlers[type])return this._dataHandlers[type];
		return this._defalutDataHandler.bind(this);
	}
	
	,_getRes:function(o){//cell默认值定义在此
		var r={'x':this.g.options.itemX};
		r.extend = function(o){$extend(r,o)};
		if(o)r.extend(o);
		return r;
	}
	
	,_rowNumDataHandler:function(item,cellData,rowData,rowNum){
		var pageNum=this.g.pageNum();
		var rows=this.g.rows();
		var realrownum=rows*(pageNum-1)+rowNum;
		
		var r=this._getRes({'value':realrownum});
		
        return r;
	}
	
	,_rowNumOnePageDataHandler:function(item,cellData,rowData,rowNum){
		var r=this._getRes({'value':rowNum});
        return r;
	}
	
	,_defalutDataHandler:function(item,cellData){
		var r;
		var html=cellData.value;
		if($chk(html))html=(''+html).replace(/&/g, "&amp;");
        var showvalue = html || '';
        if(item.get('format')) {
            showvalue = sword_fmt.convertText(item, showvalue).value;
        }
        
        r=this._getRes({'value':showvalue,'realvalue':html || "",'title':showvalue});

        if(cellData['code']) {
        	r.code=cellData['code'];
        }
        return r;
	}
	
	,_emptyDataHandler:function(item,cellData){}
	
	,_checkbox_radioDataHandler:function(item,cellData){
		var html=cellData.value;	
		var itemEl=item;
		var g=this.g;
		
		var check;
        if(g.isCP() && itemEl.get('userClicked') == 'true') {//cache+前台分页+用户点击过表头checkbox
            itemEl.get('checkAllFlag') == 'true' ? check = true : check = false;
        } else if(html == 'true' || html == '1') {
            check = 'checked="true"';
        } else {
            check = '';
        }
        
        var disabled;
        if(itemEl.get('disable') == 'true'){
        	disabled='disabled="true"';
        }else {
        	disabled='';
        }
         
        var r=this._getRes({'value':html,'checked':check ,'disabled':disabled});
        return r;
		
	}
	
	,_dateDataHandler:function(item,cellData){
		var html=cellData.value;	
		var itemEl=item;
		var g=this.g;
		var r;
		
        var sv = g.getCalendar().getShowValue(itemEl, html);
        var _sv = sword_fmt.convertText(itemEl, sv).value;
        r=this._getRes({'realvalue':html,'title':_sv,'showvalue':_sv,'value':_sv});
        cellData.originValue = _sv;
        return r;		
	}
	
	,_file2DataHandler:function(item,cellData){ 
		var html=cellData?cellData.value:'';	
		var itemEl=item;
		var r;                
	   	var d=this.g.file2_Data(html);
	   	if(d){
//	       	 s='<li class="file" id="file-id"><span class="file-title">'+d.name+'</span></li></ul></div>';
	       	 r=this._getRes({'filename':d.name,'haveData':'true'});
	   	}else{
	   		 var addCaption=itemEl.get('addCaption')||'添加文件';
//	       	 s='</ul><a name="up-attach" style="color: blue; text-decoration: underline; ">'+addCaption+'</a></div>';
	       	 r=this._getRes({'addCaption':addCaption,'haveData':'false'});
	   	}
//	   	 var s1='<div class="sword_file_upload2" name="tmp"> <ul class="up-list" name="up-list">';
	   	return r;
	}
	
	,_textDataHandler:function(item,cellData){
		var html=cellData.value;	
		var itemEl=item;
		var g=this.g;
		var r;
		
        var convertRes = sword_fmt.convertText(itemEl, html);
        var showvalue = convertRes.value+"";
        if($defined(showvalue) && $type(showvalue) == "string" && (showvalue.indexOf(">") != -1 || showvalue.indexOf("<")) != -1)showvalue = (showvalue.replace(/</g, "&lt;")).replace(/>/g, "&gt;");
        showvalue=showvalue.replace(/&/g, "&amp;");
        
        
        if(itemEl.get('type') == 'password') {
            var pw = g.dealPassword(showvalue);
            r=this._getRes({'value':pw,'title':pw,'pw':pw,'showvalue':pw});
            //todo 
//            el.store('realvalue', convertRes.realvalue);
            r.realvalue=convertRes.realvalue;
        }else{
            r=this._getRes({'value':showvalue,'title':showvalue,'realvalue':convertRes.realvalue,'showvalue':showvalue});
        }
        
        return r;
	}
	
	,_pulltreeDataHandler:function(item,cellData){
		var html;
		if($chk(cellData.code) && $chk(cellData.value)){
			html = "code,"+cellData.code+"|caption,"+cellData.value;
		}else if($chk(cellData.code)){
			html = cellData.code;
		}else{
			html = cellData.value;
		}
		var itemEl=item;
		var g=this.g;
		var r=this._getRes();
		
       
        var treename = itemEl.get('treename');
        var treeObj = $w(treename);
        var dataName=itemEl.get('dataName');

        if(treeObj.inGrid != true) {
            treeObj.inGrid = true;
        }
        if(treeObj.initDataFlag != true) { 
            treeObj.initData(pc.getInitDataByDataName(dataName));
            treeObj.initDataFlag = true;
        }


        if($chk(html)) {
            //传入的值为【code,999|caption,自然人】时，不用代码转名称，
            //这样就不用在页面初始化时加载树，减少页面加载压力,在点击时再去加载树的数据,
            //表格下拉树的懒加载方案
            if(html.contains("code") && html.contains("caption")) {
                var vs = html.split('|');
                if(html.contains('codePath')) {
                    //懒加载树的反显路径
                    r.codePath=vs[2].substring('codePath,'.length);
                }
                var text = vs[1].split(',')[1];
                var code = vs[0].split(',')[1];
                
                r.value=text;
                r.title=text;
                r.realvalue=code;
                cellData.value=code;
            } else {
                //只有code值时，需要代码转名称，不推荐这么用
                if(treeObj.gridShow != true) {
                    treeObj.select.show();
                    treeObj.options.pNode.setStyle('display', 'none');
                    treeObj.select.hide();
                    treeObj.gridShow = true;

                   g.addNextFocusEvent(treeObj.select.selBox);
                }

                var caption = '';
                var realvalue = html;
                if(treeObj.options.treeType==1){//checkbox树
                    var cl = treeObj.select.getNodeByRealvalue(realvalue);
                    var l=cl.length;
                    cl.each(function(n,i){
                    	caption=caption+n.get('caption');
                    	if(i<l-1)caption=caption+',';
                    });
                    if(caption=='')caption=realvalue;
                }else{
                    var query = new Hash();
                    query.set(treeObj.options.cascadeSign.id, html);//数据应为code值
                    var node = treeObj.getTreeNode(query);
                    
                    if(node) {
                        caption = node.get('caption');
                        realvalue = node.get(treeObj.options.cascadeSign.id);
                    } else {
                        caption = html;
                    }
                 
                }

                r.value=caption;
                r.title=caption;
                r.realvalue=realvalue;
            }
        }
		
        
        return r;
	}
	
	
	
	
	,_selectDataHandler:function(item,cellData,rowData){
		var html=(cellData.code?cellData.code:cellData.value)+"";	
		var itemEl=item;
		var g=this.g;
		var r=this._getRes();
		

        var d = html;
        if(cellData.lazydata)d = cellData.lazydata;
//        var pcode=this._getPcode(item,rowData);
//        var sel=pc.getSelect4grid();
//        sel.grid=g;
//        sel.gridMulti=this._isMulti(itemEl);
//        sel.gridSpace=null;
        var tmp =g.selDm2Mc(itemEl, d,rowData);
        var code;
        if($type(tmp) == 'object') {  //找到数据了
        	code = tmp['code'];
        	
            r.title=tmp['caption'];
            r.code=tmp['code'];
            r.realvalue=tmp["realvalue"];
            r.value=tmp['caption'];
            
            r.allDb=JSON.encode(tmp["allDb"]);
            
        } else { //没有数据
            code = html;
            
            r.title=html;
            r.code=html;
            r.realvalue=html;
            r.value=html;
        }

        //使用code作为原始值。。 ,使用realvalue作为value,提交用
        cellData.originValue = code;
        cellData.value = tmp["realvalue"] || cellData.value;
        if(html && html.contains('|')) {
        	cellData.lazydata = html;
        }

        
        return r;
	}

	
	
});
